<template>
    <!-- 游戏iframe -->
    <template v-if="isGamePlay">
        <div class="play-container">
            <iframe class="play-iframe" ref="gameIframe" :src="gamePlayUrl"></iframe>
        </div>
    </template>
    <!-- 状态 -->
    <template v-if="statusMsg">
        <div class="status-container">
            <span class="status-msg">{{ statusMsg }}</span>
        </div>
    </template>
    <!-- 登录背景图 -->
    <template v-if="isShowSdkBgImg">
        <div class="bg-img-container">
            <img class="bg-img" :src="gameBgUrl" />
        </div>
    </template>
</template>
<script>
import http from '../../../services/http'
import commons from '../../../services/commons'

export default {
    components: {
    },
    props: {
        modelValue: {
            type: Object,
            default: () => ({}),
        },
    },
    data() {
        return {
            isDebug: 1, // 是否调试
            initSucc: false, // 是否初始化完成
            userId: 0, // 登录成功userid
            game: this.modelValue.game, // 游戏
            gameChannel: this.modelValue.gameChannel, // 渠道
            gameLoginConfig: this.modelValue.gameLoginConfig, // 登录配置
            query: this.modelValue.query, // 透传参数
            isWechat: this.modelValue.isWechat, // 是否在微信客户端打开
            isPhone: this.modelValue.isPhone, // 是否在手机上打开
            gamePlayUrl: '', // 游戏入口地址
            gameBgUrl: '', // 背景图片url
            statusMsg: '', // 左上角程序状态显示
            quickLogin: {}, //quick登录信息
        };
    },
    computed: {
        isGamePlay() {
            return this.initSucc && this.gamePlayUrl;
        },
    },
    mounted() {
        this.printStatusMsg('主进程初始化中...')
        this.gamePlayUrl = this.gameChannel.game_url
        this.gameBgUrl = this.gameChannel.game_bg_url
        if (this.gameBgUrl.length > 1) {
            this.isShowSdkBgImg = 1
        }

        this.initSucc = true
        this.printStatusMsg('唤起游戏...', false)
    },
    methods: {
        // 打印调试信息
        printDebug(...args) {
            if (!this.isDebug == 1) {
                return
            }
            let now = commons.formatDate(new Date(), 'Y-m-d H:i:s.u')
            let params = Array.prototype.slice.call(args);
            console.log('[WAN SDK DEBUG]['+now+']', JSON.stringify(params))
        },
        // 打印到主屏幕上信息
        printStatusMsg(msg, auto_close = 1) {
            const _this = this
            _this.statusMsg = msg
            _this.printDebug('printStatusMsg', msg)
            if (auto_close == 1) {
                setTimeout(() => {
                    if (_this.statusMsg == msg) {
                        _this.statusMsg = ''
                    }
                }, 2000);
            }
        },
        // 向iframe发送异步消息
        postMessageToIframe(event_name, params, cbid) {
            if (this.$refs.gameIframe.contentWindow) {
                this.$refs.gameIframe.contentWindow.postMessage({
                    event_name: event_name,
                    params: params,
                    cbid: cbid
                }, '*');
            }
        },
        // 处理来自iframe的消息
        handleMessageToIframe(event_name, params, cbid) {
            const _this = this
            this.printDebug('收到iframe消息', event_name, params, cbid)
            switch (event_name) {
                case 'init':
                    _this.jssdkInit(params, cbid)
                    break;
                case 'firstupSend':
                    _this.jssdkFirstupSend(params, cbid)
                    break;
                case 'login':
                    _this.jssdkLogin(params, cbid)
                    break;
                case 'loginSuccess':
                    _this.jssdkLoginSuccess(params, cbid)
                    break;
                case 'pay':
                    _this.jssdkPay(params, cbid)
                    break;
                case 'roleReg':
                    _this.jssdkRoleReg(params, cbid)
                    break;
            }
        },
        // jssdk初始化
        jssdkInit(params, cbid) {
            const _this = this
            _this.printStatusMsg('jssdk初始化...', false)

            QuickSDK.init(_this.gameChannel.appid, _this.gameChannel.appkey, true, function(){
                _this.postMessageToIframe('init', {
                    code: 0, msg: 'success', data: {
                        query: JSON.stringify(_this.query),
                        channel: _this.gameChannel.channel,
                        game_channel_id: _this.gameChannel.id,
                    }
                }, cbid)
            })
        },
        // jssdk激活成功回调
        jssdkFirstupSend(params, cbid) {
            const _this = this
        },
        // jssdk登录
        jssdkLogin(params, cbid) {
            const _this = this
            _this.printStatusMsg('jssdk登录...', false)

            QuickSDK.login(function(res){
                // 登录失败
                if (!res.status) {
                    _this.postMessageToIframe('login', {
                        code: 9999, msg: res.message, data: {}
                    }, cbid)
                    return
                }
                _this.closeSdkBgImg()
                _this.quickLogin = res.data
                _this.postMessageToIframe('login', {
                    code: 0, msg: 'success', data: {
                        openid: res.data.uid,
                        username: res.data.username,
                        access_token: res.data.token,
                        is_login: res.data.isLogin,
                        extend_1: res.data.channelId,
                    }
                }, cbid)
            })
        },
        // jssdk登录成功
        jssdkLoginSuccess(params, cbid) {
            const _this = this
            _this.userId = params.user_id
            _this.printStatusMsg('jssdk登录成功...', false)
        },
        // jssdk支付
        jssdkPay(params, cbid) {
            const _this = this
            let order = {
                productCode: _this.gameChannel.appid,
                uid: _this.quickLogin.uid,
                username: _this.quickLogin.username,
                userRoleId: params.params.role_id,
                userRoleName: params.params.role_name,
                serverId: params.params.server_id,
                userServer: params.params.server_name,
                userLevel: params.params.role_level,
                cpOrderNo: params.trade_no,
                amount: params.params.amount,
                count: 1,
                quantifier: '个',
                subject: params.params.goods_name,
                desc: params.params.goods_name,
                goodsId: params.params.goods_id,
            }

            QuickSDK.pay(order, function(res){
                _this.printDebug('quick支付返回...', false)
            })
        },
        // jssdk角色注册
        jssdkRoleReg(params, cbid) {
            const _this = this
            let info = {
                isCreateRole: true,
                roleCreateTime: Math.floor(Date.now() / 1000),
                uid: _this.quickLogin.uid,
                username: _this.quickLogin.username,
                serverId: params.params.server_id,
                serverName: params.params.server_name,
                userRoleId: params.params.role_id,
                userRoleName: params.params.role_name,
                userRoleBalance: 0,
                vipLevel: 0,
                userRoleLevel: params.params.role_level,
                partyId: 0,
                partyName: '',
            }

            QuickSDK.uploadGameRoleInfo(info, function(res){
                //
            })
        },
        // 延迟关闭登录背景，友好的过渡到游戏页面
        closeSdkBgImg() {
            const _this = this
            setTimeout(() => {
                _this.isShowSdkBgImg = 0
            }, 1000);
        },
    },
};
</script>

<style lang="scss" scoped>
$designWidth: 640;
@function px2rem($px){
	@return calc($px*320/$designWidth/20) + rem;
}

.play-container {
    position: fixed;
    width: px2rem(640);
    height: 100%;
}

.play-iframe {
    width: 100%;
    height: 100%;
    border: none;
}

.status-container {
    position: absolute;
    z-index: 10;
    padding: px2rem(15);

    .status-msg {
        color: #fff;
        font-size: px2rem(15);
    }
}

.bg-img-container {
    width: 100%;
    height: 100%;
    aspect-ratio: 595 / 842;
    padding: 0;
    position: absolute;
    z-index: 9;
    left: 50%;
    transform: translateX(-50%);

    .bg-img {
        width: 100%;
        height: 100%;
    }
}
</style>
